package com.cute4j.diffs.cuteswing;

import java.util.Calendar;

import com.cute4j.swing.Component;
import com.cute4j.swing.Swing;
import com.cute4j.swing.Timer;
import com.cute4j.swing.events.ActionEvent;
import com.cute4j.swing.events.ActionListener;
import com.cute4j.swing.events.SwingEvent;
import com.cute4j.swing.graphics.Color;
import com.cute4j.swing.graphics.Font;
import com.cute4j.swing.graphics.Graphics;

/**
 * Custom Component.
 */
public class CustomComponent extends Component {

  private Timer timer; // <-- DIFF

  public CustomComponent() {
    enableEvents(SwingEvent.PAINT_EVENT_MASK); // <-- DIFF-
    setBackground(new Color(0, 0, 0));
    setForeground(new Color(255, 255, 255));
    timer = new Timer(500, new ActionListener() { // <-- DIFF-
      public void actionPerformed(ActionEvent e) {
        repaint();
      }
    });
    timer.start();
  }

  protected void paintComponent(Graphics g) {

    int w = getWidth();
    int w2 = w >> 1;
    int h = getHeight();
    int h2 = h >> 1;
    int cs = (w < h) ? w - 20 : h - 50;
    int cs2 = cs >> 1;
    int cs2m5 = cs2 - 5;
    int cs2m12 = cs2 - 12;
    int cs2m30 = cs2 - 30;
    double a;
    g.fillOval(w2 - 2, h2 - 2, 4, 4);
    for (int i = 0; i < 12; i++) {
      a = Math.toRadians(i * 30);
      double cosa = Math.cos(a);
      double sina = Math.sin(a);
      int x1 = w2 + (int)(cs2m5 * cosa);
      int y1 = h2 - (int)(cs2m5 * sina);
      int x2 = w2 + (int)(cs2 * cosa);
      int y2 = h2 - (int)(cs2 * sina);
      g.drawLine(x1, y1, x2, y2);
    }
    Calendar calendar = Calendar.getInstance();
    int hour = calendar.get(Calendar.HOUR);
    int minute = calendar.get(Calendar.MINUTE);
    int second = calendar.get(Calendar.SECOND);
    a = Math.toRadians(-hour * (30 + (minute >> 4)) + 90);
    int x = w2 + (int)(cs2m30 * Math.cos(a));
    int y = h2 - (int)(cs2m30 * Math.sin(a));
    g.drawLine(w2, h2, x, y);
    a = Math.toRadians(-minute * 6 + 90);
    x = w2 + (int)(cs2m12 * Math.cos(a));
    y = h2 - (int)(cs2m12 * Math.sin(a));
    g.drawLine(w2, h2, x, y);
    g.setColor(new Color(250, 0, 0));
    a = Math.toRadians(-second * 6 + 90);
    x = w2 + (int)(cs2 * Math.cos(a));
    y = h2 - (int)(cs2 * Math.sin(a));
    g.drawLine(w2, h2, x, y);
    g.setColor(new Color(150, 150, 255));
    g.setFont(g.getFont().deriveFont(Font.BOLD));
    String dt = calendar.getTime().toString();
    g.drawString(dt, w2 -
                 (g.getFontMetrics().stringWidth(dt) >> 1),
                 h - 5);
  }

  public static void main(String[] args) {
    // No EDT stuff <-- DIFF+
    // Everything is done in the GUI thread implicitly
    CustomComponent customComponent = new CustomComponent();
    customComponent.setName("Custom Component");
    customComponent.setBounds(100, 100, 200, 200);
    customComponent.setVisible(true);
    Swing.startEventLoop(); // <-- DIFF-
  }

}
